package org.example.clouddemo.controller.app;

import lombok.RequiredArgsConstructor;
import org.example.clouddemo.bean.common.entity.User;
import org.example.clouddemo.bean.common.param.LoginParam;
import org.example.clouddemo.bean.common.param.RegisterParam;
import org.example.clouddemo.bean.common.param.UpdateUserInfoParam;
import org.example.clouddemo.bean.common.vo.LoginResultVo;
import org.example.clouddemo.bean.common.vo.Result;
import org.example.clouddemo.service.common.UserService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController("appUserController")
@RequestMapping("/app/user")
@RequiredArgsConstructor
@CrossOrigin
public class UserController {

    @Qualifier("userServiceImpl")
    private final UserService userService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody RegisterParam registerParam) {
        String newUsername=userService.register(registerParam);
        Map<String,Object> map=new HashMap<>();
        map.put("username","操作成功");
        map.put("username",newUsername);

        return map;
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    // 返回值类型修正为 Result<LoginResultVo>
    public Result<LoginResultVo> login(@RequestBody LoginParam loginParam) {
        LoginResultVo loginResult = userService.login(loginParam);
        return Result.success(loginResult);
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/info")
    // 使用我们新添加的方法
    public Result<User> getUserInfo(@RequestHeader("Authorization") String token) {
        User userInfo = userService.getUserInfoByToken(token);
        // 这里返回的User对象应该做脱敏处理，将密码设置为空
        userInfo.setPassword(null);
        return Result.success(userInfo);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<Void> logout(@RequestHeader("Authorization") String token) {
        userService.logout(token);
        return Result.success();
    }

    // ...

    /**
     * 更新用户信息（昵称/头像）
     */
    @PutMapping("/update")
    public Result<Void> updateUserInfo(@RequestHeader("Authorization") String token,
                                       @RequestBody UpdateUserInfoParam param) {
        userService.updateUserInfo(token, param);
        return Result.success();
    }

}
